package com.jmcgg.freesky.common.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;
import org.apache.log4j.Logger;

public class CommonUtil {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CommonUtil.class);
	private static String sysUser = Const.FS_SYS_USER;
	private static String sysPwd = Const.FS_SYS_PWD;

	public static String genUUID() {
		return UUID.randomUUID().toString();
	}

	public static String MD5Purity(String plainText) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());

			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");

			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}

			plainText = buf.toString();
		} catch (NoSuchAlgorithmException e) {
			logger.error("MD5Purity(String) - plainText=" + plainText, e);
		}
		return plainText.toUpperCase();
	}

	public static String encodeByMd5(String str) {
		String encodeString = str;
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			encodeString = Base64Encoder.encode(md5.digest(str.getBytes("utf-8")));
		} catch (UnsupportedEncodingException e) {
			logger.error("encodeByMd5(String)", e);
		} catch (NoSuchAlgorithmException e) {
			logger.error("encodeByMd5(String)", e);
		}
		return encodeString;
	}

	public static boolean validateSysUser(String user, String pwd) {
		// validate system user and password
		if (sysUser.equals(Const.FS_SYS_USER) || sysPwd.equals(Const.FS_SYS_PWD)) {
			sysUser = ConfigUtil.getProperty(Const.FS_APP_TAG, Const.FS_SYS_USER);
			sysPwd = ConfigUtil.getProperty(Const.FS_APP_TAG, Const.FS_SYS_PWD);
		}
		if (!sysUser.equals(CommonUtil.encodeByMd5(user)))
			return false;
		if (!sysPwd.equals(CommonUtil.encodeByMd5(pwd)))
			return false;
		return true;
	}

	public static boolean isFileExist(String fileDir) {
		boolean ret = false;
		try {
			File file = new File(fileDir);
			ret = file.isFile() && file.exists();
			file = null;
		} catch (Exception ex) {
			logger.error("isExist(String)", ex);
		}
		return ret;
	}

	public static void saveToFile(List<String> list, String filePath) {
		try {
			File file = new File(filePath);
			FileUtils.writeLines(file, list);
		} catch (IOException ex) {
			logger.error("saveToFile(List<String>, String)", ex);
		}
	}

	public static boolean copyFile(String src, String dest) {
		boolean ret = false;
		if (src == null || dest == null || src.length() == 0 || dest.length() == 0) {
			ret = false;
			logger.error("The parameter are wrong.");
			return ret;
		}
		try {
			File srcFile = new File(src);
			File destFile = new File(dest);
			FileUtils.copyFile(srcFile, destFile);
			ret = true;
		} catch (Exception e) {
			logger.error("copyFile(String, String) - String src=" + src + ", String dest=" + dest, e);

			ret = false;
		}
		return ret;
	}

	public static boolean copyFile(File srcFile, File destFile) {
		try {
			FileUtils.copyFile(srcFile, destFile);
			return true;
		} catch (IOException e) {
			logger.error("copyFile(File, File) - File srcFile=" + srcFile + ", File destFile=" + destFile, e);
			return false;
		}
	}

	public static boolean deleteFile(String srcFile) {
		File file = new File(srcFile);
		if (file != null && file.exists())
			return file.delete();
		return false;
	}

	public static String getExt(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}

	public static String getFSTime() {
		String time = "";
		SimpleDateFormat sdf = new SimpleDateFormat(Const.FS_DATE_FORMAT);
		time = sdf.format(Calendar.getInstance().getTime());
		return time;
	}

	public static String getFSDate() {
		return getFSTime().substring(0, 10);
	}

	public static String getFSDate(Date time) {
		return getFSTime(time).substring(0, 10);
	}

	public static String getFSTime(Date time) {
		SimpleDateFormat sdf = new SimpleDateFormat(Const.FS_DATE_FORMAT);
		return sdf.format(time);
	}

	public static Date parseFSTime(String fsTime) {
		Date time;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(Const.FS_DATE_FORMAT);
			time = sdf.parse(fsTime);
		} catch (ParseException e) {
			logger.error("parseFSTime(String)", e);
			time = new Date();
		}
		return time;
	}

	public static String date2Str(Date d) {
		if (d == null)
			return "";
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(d);
	}

	public static Date str2Date(String s) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d = new Date();
		try {
			d = df.parse(s);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return d;
	}

	public static boolean sendEmail(String sendTo, String title, String content) {
		try {
			Email email = new SimpleEmail();
			email.setHostName(ConfigUtil.getProperty(Const.FS_APP_TAG, Const.EMAIL_HOST_NAME));
			email.setSmtpPort(Integer.parseInt(ConfigUtil.getProperty(Const.FS_APP_TAG, Const.EMAIL_SMTP_PORT)));
			email.setAuthenticator(new DefaultAuthenticator(ConfigUtil.getProperty(Const.FS_APP_TAG,
					Const.EMAIL_USER_ID), DESUtil.getInstance().decrypt(
					ConfigUtil.getProperty(Const.FS_APP_TAG, Const.EMAIL_PASSWORD))));
			// It is a 1.3 feature. email.setSSLOnConnect(true);
			email.setSSL(true);
			email.setFrom(ConfigUtil.getProperty(Const.FS_APP_TAG, Const.EMAIL_ADDRESS));
			email.setSubject(title);
			email.setMsg(content);
			email.addTo(sendTo);
			email.send();
			return true;
		} catch (Exception e) {
			logger.error("sendEmail(String, String, String)", e);
			return false;
		}
	}
}